/**
 * 获取随机数的函数
 * @param {number} a 表示范围的数字
 * @param {number} b 表示范围的数字
 * @returns number 范围内的随机数
 */
function getRandom(a, b) {
    var max = a
    var min = b
    if(a<b) {
        max = b
        min = a
    }
    var num = parseInt(Math.random() * (max - min)) + min
    return num
}
/**
 * 获取随机颜色值的函数
 * @param {number} n 必须是16，表示是否获取16进制的颜色值
 * @returns 16进制的或rgb的颜色值
 */
function getColor(n) {
    if(n === 16) {
        var color = '#'
        for(var a=0; a<3; a++) {
            var num = getRandom(0, 256)
            var hex = num.toString(16)
            if(hex.length === 1) {
                hex = '0' + hex
            }
            color += hex
        }
        return color
    } else {
        var str = 'rgb('
        var arr = []
        for(var a=0; a<3; a++) {
            arr.push(getRandom(0, 256))
        }
        str += arr.join()
        str += ')'
        return str
    }
}
/**
 * 批量设置样式的函数
 * @param {node} ele 要设置样式的标签
 * @param {object} obj 要设置的样式组成的键值对对象
 */
function setStyle(ele, obj) {
    for(var key in obj) {
        ele.style[key] = obj[key]
    }
}
/**
 * 动画函数
 * @param {node} ele 要执行动画的标签节点
 * @param {object} obj 动画的css键值对组成的对象
 * @param {function} fn 所有动画结束要执行的函数
 */
function animate(ele, obj, fn = function() {}) {
    let k = 0
    for(let key in obj) {
        k++
        let target = obj[key]
        let currentStyle = getComputedStyle(ele)[key]
        if(key === 'opacity') {
            currentStyle *= 100
            target *= 100
        }
        currentStyle = parseInt(currentStyle)
        let timer = setInterval(function() {
            let speed = (target - currentStyle) / 20
            currentStyle += speed > 0 ? Math.ceil(speed) : Math.floor(speed)
            if(key === 'opacity') ele.style[key] = currentStyle / 100
            else ele.style[key] = currentStyle + 'px'
            if(currentStyle === target) {
                clearInterval(timer)
                if(--k === 0) fn()
            }
        }, 20)
    }
}
/**
 * 发送ajax请求的函数
 * @param {object} obj 
 */
function ajax(obj) {
    if(obj.async === undefined) {
        obj.async = true
    }
    if(typeof obj.async != 'boolean') {
        throw new Error('非法访问')
    }
    
    if(obj.method === undefined) {
        obj.method = 'get'
    }
    if(obj.method != 'get' && obj.method != 'post') {
        throw new Error('请求方式非法')
    }
    if(obj.url === undefined) {
        throw new Error('请求地址不能为空')
    }
    if(obj.fn === undefined) {
        obj.fn = function(){}
    }
    if(typeof obj.fn != 'function') {
        throw new Error('fn必须是函数')
    }
    var data
    if(obj.data != undefined) {
        if(Object.prototype.toString.call(obj.data) === '[object String]') {
            data = obj.data
        } else if(Object.prototype.toString.call(obj.data) === '[object Object]') {
            var arr = []
            for(var key in obj.data) {
                arr.push(key + '=' + obj.data[key])
            }
            data = arr.join('&')
        } else {
            throw new Error('数据非法')
        }
        if(data != undefined && obj.method === 'get') {
            obj.url += '?' + data
        }
    }
    var xhr = new XMLHttpRequest;
    xhr.open(obj.method, obj.url, obj.async);
    if(data != undefined && obj.method === 'post') {
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(data)
    } else {
        xhr.send()
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status>=200 && xhr.status<300){
                var res = xhr.responseText;
                obj.fn(res)
            }
        }
    }
}
/**
 * 设置cookie的函数
 * @param {string} key 要设置的cookie的键
 * @param {string} value 要设置的cookie的值
 * @param {number} seconds 要设置cookie多少秒之后失效
 * @param {string} path 设置cookie的路径
 */
function setCookie(key, value, seconds, path = '/') {
    var date = new Date()
    var newTime = date.getTime()-8*3600*1000+seconds*1000
    date = new Date(newTime)
    document.cookie = `${key}=${value};expires=${date};path=${path}`
}
/**
 * 删除cookie的函数
 * @param {string} key 要删除的cookie的键
 * @param {string} path 要删除的cookie的路径
 */
function removeCookie(key, path = '/') {
    setCookie(key, null, -1, path)
}
/**
 * 获取cookie的函数
 * @param {string} key 要获取的cookie的键
 * @return {string} 返回获取到的键对应的值
 */
function getCookie(key) {
    var arr = document.cookie.split('; ')
    for(var a=0; a<arr.length; a++) {
        var brr = arr[a].split('=')
        if(brr[0] === key) {
            return brr[1]
        }
    }
}

function promiseAjax(obj) {
    return new Promise(function(resolve, reject) {
        if(obj.async === undefined) {
            obj.async = true
        }
        if(typeof obj.async != 'boolean') {
            throw new Error('非法访问')
        }
        
        if(obj.method === undefined) {
            obj.method = 'get'
        }
        if(obj.method != 'get' && obj.method != 'post') {
            throw new Error('请求方式非法')
        }
        if(obj.url === undefined) {
            throw new Error('请求地址不能为空')
        }
        var data
        if(obj.data != undefined) {
            if(Object.prototype.toString.call(obj.data) === '[object String]') {
                data = obj.data
            } else if(Object.prototype.toString.call(obj.data) === '[object Object]') {
                var arr = []
                for(var key in obj.data) {
                    arr.push(key + '=' + obj.data[key])
                }
                data = arr.join('&')
            } else {
                throw new Error('数据非法')
            }
            if(data != undefined && obj.method === 'get') {
                obj.url += '?' + data
            }
        }
        var xhr = new XMLHttpRequest;
        xhr.open(obj.method, obj.url, obj.async);
        if(data != undefined && obj.method === 'post') {
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            xhr.send(data)
        } else {
            xhr.send()
        }
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status>=200 && xhr.status<300){
                    var res = xhr.responseText;
                    resolve(res)
                } else {
                    reject()
                }
            }
        }
    })
}